<template>
  <div class="Role">
    <div class="page-head">
      <div class="page-title">
        消息通知
      </div>
      <div class="page-tool">
        <search-input placeholder="消息标题" @search="searchChange" />
        <div class="tool-btn" v-if="$permiss(btnPermiss, '新增')" @click="open('add')">新 增</div>
      </div>
    </div>
    <div class="page-body">
      <div class="table_data">
        <el-scrollbar class="scroll-bar">
          <el-table :data="tableData" stripe>
            <el-table-column
              width="20"
            />
            <el-table-column
              prop="title"
              label="消息标题"
            >
              <template slot-scope="{row}">
                <div class="ellipsis">
                  {{row.title}}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="content"
              label="消息内容"
            >
              <template slot-scope="{row}">
                <div class="ellipsis">
                  {{row.content}}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="last_send_time"
              label="发送时间"
              width="160"
            >
              
            </el-table-column>
            <el-table-column label="操作" width="220" align="center">
              <template slot-scope="{row}">
                <div class="operation-col">
                  <div
                    v-if="$permiss(btnPermiss, '查看')"
                    class="txt-btn ope-btn primary"
                    @click="look(row)"
                  >
                    查看
                  </div>
                  <div
                    v-if="$permiss(btnPermiss, '发送')"
                    class="txt-btn ope-btn primary"
                    :class="{'grey notAllow': row.last_send_time !== null }"
                    @click="send(row)"
                  >
                    发送
                  </div>
                  <div
                    v-if="$permiss(btnPermiss, '修改')"
                    class="txt-btn ope-btn primary"
                    :class="{ 'grey notAllow' : row.last_send_time !== null }"
                    @click="open('edit', row)"
                  >
                    修改
                  </div>
                  <div
                    v-if="$permiss(btnPermiss, '删除')"
                    class="txt-btn error"
                    :class="{'grey notAllow': row.last_send_time !== null}"
                    @click="doDelete(row)"
                  >
                    删除
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-scrollbar>
      </div>
      <div class="page-footer">
        <pagina-tion
        class="page-pager"
        v-show="total>=0"
        :background="true"
        :total="total"
        :offset.sync="offset"
        :limit.sync="limit"
        @pagination="getChangePage"
      />
      <button  class="page-button">确定</button>
      </div>
     
    </div>

    <!-- 查看弹框 -->
    <el-dialog :visible.sync="lookVisable" width="900px" title="消息详情" :close-on-click-modal="false" @close="closeLook">
      <div class="dialog-body detail-body">
        <el-form ref="form" label-width="90px" label-position="left">
          <el-form-item label="消息标题：" class="mb10">
            {{detail.title}}

          </el-form-item>
          <el-form-item label="消息内容：" class="mb10">
            {{detail.content}}
          </el-form-item>
          <el-form-item label="图片：" class="mb10">
            <img :src="detail.pic" class="upload-img">
          </el-form-item>

        </el-form>
      </div>
    </el-dialog>

    <!-- 新增和修改弹框 -->
    <el-dialog :visible.sync="model.visible" width="450px" :title="model.type==='add'?'新增消息':'修改消息'" :close-on-click-modal="false" :show-close="false">
      <div class="dialog-body">
        <el-form ref="form" :model="form" label-width="90px" label-position="left">
          <el-form-item label="消息标题" class="required">
            <el-input
              v-model="form.title"
              name="noticeTitle"
              v-validate="'required'"
              placeholder="请输入消息标题"
              :maxlength="32"
            />
            <div v-show="errors.has('noticeTitle')" class="el-form-item__error">{{ errors.first('noticeTitle') }}</div>
          </el-form-item>
          <el-form-item label="消息内容" class="required">
            <el-input
              v-model="form.content"
              name="noticeContent"
              v-validate="'required'"
              placeholder="请输入消息内容"
              type="textarea"
              :maxlength="500"
            />
            <div v-show="errors.has('noticeContent')" class="el-form-item__error">{{ errors.first('noticeContent') }}</div>
          </el-form-item>
          <el-form-item label="图片" class="required">
            <el-upload
              class="avatar-uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
              :show-file-list="false"
              :http-request="uploadReq"
              :before-upload="beforeAvatarUpload"
              :accept="imgAccept"
            >
              <img v-if="form.pic" key="pic" :src="form.pic" class="upload-img">
              <img v-else key="default" src="~assets/img/upload.png" class="upload-img">
            </el-upload>
            <el-input
              name="noticePic"
              v-validate="'required'"
              type="hidden"
              v-model="form.pic"
            ></el-input>
            <div v-show="errors.has('noticePic')" class="el-form-item__error">{{ errors.first('noticePic') }}</div>
          </el-form-item>

        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="close">取 消</el-button>
        <el-button type="primary" @click="submit">保 存</el-button>
      </span>
    </el-dialog>
    <!-- 删除弹窗 -->
    <el-dialog
      :visible.sync="visibility"
      width="430px"
      height="100px"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="dialog-content comfirm-body">
        <img class="comfirm-ico"
             src="~assets/img/warning.png">
        <div class="comfirm-txt">
          <div>
            确定删除该条数据？
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="visibility = false">取 消</el-button>
        <el-button type="primary" @click="notificationDelete">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Loading } from 'element-ui'
import { format } from 'silly-datetime'
import * as api from '@/api'
import { limit,middleLimit, imgAccept  } from '@/consts/consts'
import { noticeFormKey } from '@/consts/formKey'
import client from '@/utils/oss'

export default {
  data() {
    return {
      btnPermiss: [],
      format,
      limit:document.body.clientHeight>= 770 ? limit : middleLimit,
      imgAccept,
      total: 0,
      offset: 0,
      tableData: [],
      model: {
        type: 'add',
        visible: false
      },
      visibility: false,
      lookVisable: false,
      detail: {},
      id: '',
      form: {
        ...noticeFormKey
      },
      uploadFile: null,
      isHasPermission: {
        addChecked: true,
        editChecked: true,
        deletChecked: true
      },
      loading: null
    }
  },
  methods: {
    look(row) {
      this.detail = row
      this.lookVisable = true
    },

    closeLook() {
      this.detail = {}
      this.lookVisable = false
    },

    open(type, row=null) {
      this.$validator.reset()
      this.model.type = type
      if (row) {
        if(row.last_send_time != null){
          return false
        }
        for (const k in noticeFormKey) {
          this.form[k] = row[k]
        }
        this.id = row.id
      }
      this.model.visible = true
    },
    
    getChangePage(val) {
      this.offset = val.offset
      this.notificationList()
    },
    
    searchChange(e) {
      this.search = e
      this.offset = 0
      this.notificationList()
    },
    
    close() {
      this.model.visible = false
      this.form = {...noticeFormKey}
    },
    
    doDelete(row) {
      if (row.last_send_time) {
        return false
      }
      this.id = row.id
      this.visibility = true
    },

    send(row) {
      if (row.last_send_time) {
        return false
      }
      this.id = row.id
      this.notificationSend()
    },

    beforeAvatarUpload(file) {
      const typeOk = ['image/png', 'image/PNG', 'image/jpg', 'image/JPG', 'image/jpeg', 'image/JPEG'].includes(file.type)
      if (typeOk) {
        this.uploadFile = file;
        return true;
      } else {
        return this.$message.warning('只支持png、jpg格式的图片')
      }
    },
    
    submit() {
      this.$validator.validateAll().then(valid => {
        if (valid) {
          this.addOrEdit()
        } else {
          this.$message.warning('有信息未填写正确')
        }
      })
    },
        
    async uploadReq() {
      let [n, suf] = this.uploadFile.name.split('.')
      let fileName = `${n}_${+new Date}.${suf}`
      this.loading = Loading.service({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      let result = await client.put(`message/${fileName}`, this.uploadFile)

      if (result) {
        this.form.pic = result.res.requestUrls[0]
        this.loading.close()
      }


      // let formData = new FormData()
      // formData.append('bucket', 'message')
      // formData.append('file', this.uploadFile)
      // const { code, data } = await api.upload(this).upload(formData)
      // if (code === 0) {
      //   this.form.pic = data.url 
      // }
    },

    async notificationList() {
      const { code, data, total } = await api.notice(this).notificationList({
        offset: this.offset,
        limit:this.limit,
        title: this.search
      })
      if (code === 0) {
        this.tableData = data
        this.total = total
      }
    },
    
    async notificationSend() {
      const { code } = await api.notice(this).notificationSend({
        id: this.id
      })
      if (code === 0) {
        this.$message.success('操作成功')
        this.close()
        this.notificationList()
      }
    },

    
    async addOrEdit() {
      let fn = this.model.type === 'add' ? 'notificationAdd' : 'notificationUpdate'
      const { code } = await api.notice(this)[fn](this.form, this.id)
      if (code === 0) {
        this.$message.success('操作成功')
        this.close()
        this.notificationList()
      }
    },

    async notificationDelete() {
      const { code } = await api.notice(this).notificationDelete(this.id)
      if (code === 0) {
        this.$message.success('操作成功')
        this.id = ''
        this.visibility = false
        if (this.total % this.limit === 1) {
          if (this.offset >= this.limit) {
            this.offset -= this.limit
          }
        }
        this.notificationList()
      }
    },
  },
  
  created() {
    this.notificationList()
    let permission =JSON.parse( localStorage.getItem('permission'))
    let curMenu = permission.find(item => item.txt === "消息通知")
    this.btnPermiss = curMenu.btns
  }
}
</script>

<style lang="stylus">
.Notice {
}
</style>